layui.define(["msg", "ajax", "utils", "element", "form", "sortMap"], function(exports){
	var $ = layui.jquery;
	var layer = layui.layer;
	var conf = layui.conf;
	var utils = layui.utils;
	var ajax = layui.ajax;
	var conf = layui.conf;
	var element = layui.element;
	var form = layui.form;
	var msg = layui.msg;
	var pageDataMap = layui.sortMap.create(10);
	
	
	admin = {
		render : function(href, target, o){
			if(!target){
				target = conf.defaultTarget;
			}else if(typeof(target) === 'string'){
				target = target || conf.defaultTarget;
			}else{
				o = target;
				target = conf.defaultTarget;
			}
			if(target === 'iframe' || target === 'blank' || target === 'dialog'){
				admin.redirect(href, target, o);
			}else{
				if(target == conf.defaultTarget){
					location.hash = utils.parseRouter(href);
				}else{
					location.hash = utils.addUrlPara("t", utils.stringToHex(target), utils.parseRouter(href));
				}
			}
		},
		redirect : function(url, target, o = {}){			
			url = url || "";
			//忽略http和https的链接解析
			if(!(/^http:\/\/|^https:\/\//.test(url) || /^[#\.]/.test(url))){
				url = utils.parseRouter(url);
				var hasPara = /[?]/.test(url);
				urlSplit = hasPara ? url.split("?") : [url, ""];
				var href = urlSplit[0];
				if(!/\..*$/.test(href)){
					href = (conf.pagePrefix + href).replace(/(\/+)/g, "/");
					href = /\/$/.test(href) ? href + conf.pageDefallt + conf.pageSuffix : href + conf.pageSuffix;
				}
				url = hasPara ? href + "?" + urlSplit[1] : href;
			}
			target = target || conf.defaultTarget;
			
			//打开一个新窗口
			if("blank" === target){
				window.open(url)
				return;
			}
			
			//打开一个iframe层
			if("iframe" === target){
				layer.open($.extend({
					type : 2,
					maxmin: true,
					area : conf.iframeDefaultArea, 
					content : url
				}, o));
				return;
			}
			
			if(/^[#\.]/.test(url) && "dialog" === target){
				layer.open($.extend({
					type : 1,
					area : conf.dialogDefaultArea, 
					content : $(url).html(),
					end : function(){
						if(o.pageId){
							endCb && endCb(pageDataMap.get(o.pageId)["okCallBack"])
							pageDataMap.remove(o.pageId);
						}
					}
				}, o));
				form.render();
				return;
			}
			
			msg.load();
			return $.ajax({
				url : conf.debug ? utils.addUrlPara("_", new Date().getTime() ,url) : url,
				type: "get",
	            dataType: "html",
	            cache: utils.isBlank(conf.debug) ? true : !conf.debug,
	            success : function(respHtml){
	            	//弹出dialog层
	            	var endCb = o.end;
	            	delete o.end;
	            	//预先计算layer的index
	            	o.pageId && (pageDataMap.add(o.pageId, $.extend({}, o.p, {
	            		index : layer.index + 1,
	            		okCallBack : false,
	            	})));
	            	if("dialog" === target){
	            		var index = layer.open($.extend({
	    					type : 1,
	    					area : conf.dialogDefaultArea, 
	    					content : respHtml,
	    					end : function(){
	    						if(o.pageId){
	    							endCb && endCb(pageDataMap.get(o.pageId)["okCallBack"])
	    							pageDataMap.remove(o.pageId);
	    						}
	    					},
	    					cancel : function(index, dom){
	    						o.pageId && admin.pageData(o.pageId)["cancel"] && admin.pageData(o.pageId)["cancel"](index, dom);
	    					},
	    					full : function(dom){
	    						o.pageId && admin.pageData(o.pageId)["full"] && admin.pageData(o.pageId)["full"](dom);
	    					},
	    					min : function(dom){
	    						o.pageId && admin.pageData(o.pageId)["min"] && admin.pageData(o.pageId)["min"](dom);
	    					},
	    					restore  : function(dom){
	    						o.pageId && admin.pageData(o.pageId)["restore"] && admin.pageData(o.pageId)["restore"](dom);
	    					}
	    				}, o));
	            		o.max && layer.full(index);
	    			}else{
	    				//设置到页面
	    				$(target).html(respHtml)
	    			}
	            	
	            	//渲染表单
	            	try{
	            		$(respHtml).find(".layui-form")[0] && form.render();
	            		$(respHtml).find("button[data-submit]").each(function(){
	            			var $this = $(this);
	            			var filter = $this.attr("lay-filter");
	            			admin.listenformSubmit(filter, o.pageId)
	            		})
	            	}catch(e){
	            		
	            	}
	            	
	            },
	            error : function(e, a){
	            	if("dialog" === target){
	            		msg.error("页面加载失败");
	            	}else{
	            		console.log(e.responseText)
	            		console.log(a)
	            		$(target).html(e.responseText)
	            	}
	            }
				
			}).always(function(){
				msg.removeLoad();
			})
		},
		/**form表单自动填充数据和渲染*/
		autoBind : function(elem, url, data, o){
			var bindOk = o.ok;
			delete o.ok;
			delete o.fail;
			ajax.get(url, data, $.extend({
				showTip : false,
				ok : function(resp){
					if(typeof(conf.response.formBindDataName) == 'string'){
						admin.formBind(elem, utils.getDictData(resp, conf.response.formBindDataName), o.filter);
					}else{
						for(i in conf.response.formBindDataName){
							admin.formBind(elem, utils.getDictData(resp, conf.response.formBindDataName[i]), o.filter);
						}
					}
					bindOk && bindOk(resp);
				},
				fail : function(resp){
					msg.error(resp[conf.response.msgName]);
					o.errorClose && o.dialogIndex && layer.close(o.dialogIndex);
				}
			}, o));
		},
		formBind : function(elem, data, filter){
			var $form = $(elem);	
			if(data){
				for(key in data){
					var items = $form.find("[name='" + key + "']") || $form.find("[data-bind='" + key + "']");
					for(var i = 0 ; i < items.length ; i++){
						var item = items[i];
						if(item.hasAttribute("data-ignore")){
							continue;
						}
						var componentName = item.localName;
						if(item.type == 'radio'){
							//设置radio选中
							for(var i in items){
								if(items[i].value == data[key]){
									items[i].checked = true;
								}
							}
							break;
						}
						item.value = data[key];
					}
				}
				filter ? layui.form.render(null,filter) : layui.form.render();
			}
			
		},
		listenformSubmit : function(filter, pageId, o = {}){
			if(filter){
				var form = layui.form;
				form.on("submit(" + filter +")", function(data){
					var $elem = $(data.elem);
					var option = eval('(' + $elem.data("option") + ')');
					o = $.extend({close : true},option, o)
					var url = o.submit || o.url || $elem.data("submit");
					var submitOk = o.ok; 
					delete o.ok;
					ajax.req(url, data.field,$.extend({
						method : "POST",
						ok : function(resp){
							if(pageId){
								if(utils.isBlank(o.okcallback)){
									admin.setPageCallBackData(pageId, o.okcallback)
								}else{
									admin.setPageCallBackData(pageId, true);
								}
							} 
							submitOk && submitOk(resp);
							o.close && pageId && admin.layerClose(pageId);
						}
					}, o));
					return false;
				})
			}
		},
		pageData : function(pageId){
			return pageDataMap.get(pageId);
		},
		setPageCallBackData : function(pageId, o){
			if(typeof(o) === 'function'){
				return;
			}
			pageDataMap.get(pageId)["okCallBack"] = o;
		},
		layerClose : function(pageId){
			if(typeof(pageId) === 'string'){
				pageDataMap.get(pageId) && layui.layer.close(pageDataMap.get(pageId)["index"]);
			}else{
				layui.layer.close(pageId)
			}
		},
		refreshLeftNav : function(){
			/**处理左侧菜单栏选中*/	
			var elem = null;
			var href = layui.router().href;
			href != '/'  && utils.isBlank(href) || $("#admin-side-menu *[data-render]").each(function(i, e){
				var renderHref = utils.parseRouter($(e).data("render"));
				if(renderHref === href){
					elem = e;
					return false;
				}
			});
			$("#admin-side-menu .layui-nav-itemed").removeClass("layui-nav-itemed");
			$("#admin-side-menu .layui-this").removeClass("layui-this");
			if(elem != null){
				var $e = $(elem);
				var $dd = $e.parent("dd");
				if($dd.length > 0){
					$e.parent("dd").addClass('layui-this');
				}else{
					$e.parent(".layui-nav-item").addClass('layui-this');
				}
				$e.parents(".layui-nav-item").addClass("layui-nav-itemed");
			}
		},
		getToken : function(){
			return layui.data(conf.tableName)[tokenName];
		},
		setToken : function(token){
			layui.data(conf.tableName)
		},
		msg : layui.msg,
		utils : utils,
		ajax : layui.ajax
	}
	
	
	$("body").on("click", "*[data-render]", function(e){
		var $this = $(this);
		var confirm = $this.data("confirm");
		var fun = function(){
			var href = $this.data("render");
			var target = $this.data("target");
			var pageId = $this.data("pageid");
			var option = eval('(' + $this.data("option") + ')');
			p = eval('(' + $this.data("data") + ')');
			p && (option.p = p);
			pageId && $.extend(option, {
				pageId : pageId
			})
			admin.render(href, target, option);
		}
		if(confirm){
			msg.confirm(confirm, function(index){
				admin.layerClose(index);
				fun();
			}, function(){
				admin.refreshLeftNav();
			})
		}else{
			fun();
		}
		
	}).on("click", "*[data-href]", function(e){
		var $this = $(this);
		var confirm = $this.data("confirm");
		var fun = function(){
			var href = $this.data("href");
			var method = $this.data("method") || "get";
			var data = eval('(' + $this.data("data") + ')');
			var option = eval('(' + $this.data("option") + ')');
			if(method === 'get'){
				ajax.get(href, data, option);
			}else{
				ajax.post(href, data, option);
			}
		}
		if(confirm){
			msg.confirm(confirm, function(index){
				admin.layerClose(index);
				fun();
			})
		}else{
			fun();
		}
		
	});
	
	
	
	exports("admin", admin)
})